using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Wombat.Core.Services
{
    public class TagRpository : ITagRpository, ITagRepositoryLoader
    {
        private ConcurrentDictionary<Guid, ITag> _tagLookupByGuid = new ConcurrentDictionary<Guid, ITag>();
        private ConcurrentDictionary<long, ITag> _tagLookupById = new ConcurrentDictionary<long, ITag>();
        private object _sync = new object();

        public ITag Get(Guid tagId)
        {
            return _tagLookupByGuid[tagId];
        }

        public ITag Get(long tagId)
        {
            return _tagLookupById[tagId];
        }

        public async Task LoadAsync(IEnumerable<Tag> tags)
        {
            await Task.Factory.StartNew(
                () =>
                    {
                        var tagsList = tags.ToList();
                        lock (_sync)
                        {
                            _tagLookupByGuid = new ConcurrentDictionary<Guid, ITag>
                                (tagsList.Select(t => new KeyValuePair<Guid, ITag>(t.UniqueId, t)));
                            _tagLookupById = new ConcurrentDictionary<long, ITag>
                                (tagsList.Select(t => new KeyValuePair<long, ITag>(t.PersistedId, t)));
                        }
                    });
        }
    }
}